#include "fuHttpRequest.h"
#include "_Sockets-2.3.5/HttpGetSocket.h"
#include "_Sockets-2.3.5/SocketHandler.h"

#define MAX_DOC_SIZE 32000

BEGIN_NAMESPACE_CPPX

cppx::fuString fuHttpResponse::GetEncode( void )
{
    if( ContentType.StartsWith("text/html") ){
        bool UTF8_flag(false);
        UTF8_flag |= ContentType.Equals("text/html;charset=UTF-8");
        UTF8_flag |= ContentType.Equals("text/html") && Document.substr(0,3) == "\xEF\xBB\xBF";
        if( UTF8_flag )
            return "UTF-8";
        bool Unicode_flag(false);
        Unicode_flag |= ContentType.Equals("text/html") && Document.substr(0,3) == "\xEF\xBB\xBF";
        return "ANSI";
    }
    return "other";
}

fuHttpRequest::fuHttpRequest(void)
{
}

fuHttpRequest::~fuHttpRequest(void)
{
}

bool fuHttpRequest::Get( const fuString& url_in,fuHttpResponse& response )
{
	SocketHandler handler;
	HttpGetSocket socket(handler, url_in);
	if( !socket.CloseAndDelete() ){
		unsigned char p[MAX_DOC_SIZE] = {0};
		socket.SetDataPtr(p, MAX_DOC_SIZE-1);			// preserve '\0' at end of document
		handler.Add(&socket);

		do{
			handler.Select(1,0);
		}
		while( handler.GetCount() );

		bool complete = socket.Complete();
		if (complete){
			response.Content		= socket.GetContent();
			response.ContentType	= socket.GetContentType();
			response.ContentLength	= socket.GetContentLength();
			response.Document		= (char *)socket.GetDataPtr();
		}
		return complete;
	}
	return false;
}

fuString fuHttpRequest::host2ip( const std::string & host )
{
	fuString ip;
	ipaddr_t addr;
	if( Utility::u2ip(host,addr) )
		Utility::l2ip(addr,ip);
	return ip;
}

END_NAMESPACE_CPPX
